//http://192.1681.177/?setCon=0&getCon=0

#include <SPI.h>        
#include <Ethernet.h>
#include <TextFinder.h>
#include <DateTime.h>
#include "DHT.h"

// macros from DateTime.h 
/* Useful Constants */
#define STRING_BUFFER_SIZE 128
#define SECS_PER_MIN  (60UL)
#define SECS_PER_HOUR (3600UL)
#define SECS_PER_DAY  (SECS_PER_HOUR * 24L)
#define DHTPIN 5
#define DHTTYPE DHT11   // DHT 11
 
/* Useful Macros for getting elapsed time */
#define numberOfSeconds(_time_) (_time_ % SECS_PER_MIN)  
#define numberOfMinutes(_time_) ((_time_ / SECS_PER_MIN) % SECS_PER_MIN) 
#define numberOfHours(_time_) (( _time_% SECS_PER_DAY) / SECS_PER_HOUR)
#define elapsedDays(_time_) ( _time_ / SECS_PER_DAY)  


byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 177 };
long inicial = 0, final = 0, tempo = 0;
EthernetClient client;
TextFinder finder( client );
EthernetServer server(80);
DHT dht(DHTPIN, DHTTYPE);

static char buffer[STRING_BUFFER_SIZE];
static char tempBuffer[15];
static char humBuffer[15];


void setup() {

Serial.begin(9600);
Ethernet.begin(mac, ip);
server.begin();
dht.begin();
Serial.println("ready");
}

void loop() {
  client = server.available();
  if (client) {                
    while (client.connected()) {
      if (client.available()) {
        if (client.find("GET /")) {
          
          //INICIAR CRONOMETRAGEM
          if (client.find("setCron=")) {
            int charReaded = client.read();
			if(charReaded == 49){
              iniciarCronometragem();
            }
          }
		  
		   //RETORNA O TEMPO DESDE O INICIO		  
          if (client.find("getCron=")) {
            int charReaded = client.read();
			if(charReaded == 49){
              getCronometragem();
			}
          }

		  //RETORNA TEMPERATURA
		  if (client.find("getTemp=")) {
            int charReaded = client.read();
			if(charReaded == 49){
              getTemperature();
			}
          }

		  //RETORNA HUMIDADE
		  if (client.find("getHum=")) {
            int charReaded = client.read();
			if(charReaded == 49){
              getHumidity();
			}
          }

        }
      }
      Serial.println();
      break;
    }
    client.println(" HTTP/1.1 200 OK ");
  }
  // give the web browser time to receive the data
  delay(1);
  client.stop();
}

void printChaveValorJson(String chave, String valor) {

  client.print("\"");
  client.print(chave);
  client.print("\"");
  client.print(":");
  client.print("\"");
  client.print(valor);
  client.println("\",");

}

void printHeader() {

  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: application/json");
  client.println("Connnection: close");
  client.println();
  client.println("{");

}

void printFooter() {

  client.print("\"");
  client.print("THE");
  client.print("\"");
  client.print(":");
  client.print("\"");
  client.print("END");
  client.println("\"");

  client.print("}");
}
void getCronometragem() {

  Serial.println("pegando a cronometragem...");
  long result = (long) millis() - inicial;
  
  int days = elapsedDays(result);
  int hours = numberOfHours(result);
  int minutes = numberOfMinutes(result);
  int seconds = numberOfSeconds(result);

  // digital clock display of current time
  Serial.print(days,DEC);  
  printDigits(hours);  
  printDigits(minutes);
  printDigits(seconds);
  Serial.println();  
  
  printHeader();
  printChaveValorJson("TEMPO TOTAL", (String) result);
  printFooter();
  
}

void printDigits(byte digits){
  // utility function for digital clock display: prints colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits,DEC);  
}

void iniciarCronometragem() {
 Serial.println("iniciando a cronometragem...");
 inicial = (long) millis();
}

void printClient(EthernetClient client){
  int i=0;
    char c = client.read();
    while(c != '\n' && c != '\r'){	
    buffer[i] = c;		
    i++;
    c = client.read();		
  }
  for(int j=0; j<i; j++){
  Serial.write(buffer[j]);
  }
}

void getTemperature(){

float temp = dht.readTemperature();

if (isnan(temp)) {
    Serial.println("Failed to read from DHT");
  } else {

	dtostrf(temp,8, 2, tempBuffer);

	printHeader();
	printChaveValorJson("TEMPERATURA (CELSaIUS)", tempBuffer);
	printFooter();
  }
}

void getHumidity(){

float hum = dht.readHumidity();

if (isnan(hum)) {
    Serial.println("Failed to read from DHT");
  } else {

	dtostrf(hum,8, 2, humBuffer);

    printHeader();
	printChaveValorJson("HUMIDADE", humBuffer);
	printFooter();
  }
}




